package com.atguigu.daijia.rules.config;

import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieModule;
import org.kie.api.runtime.KieContainer;
import org.kie.internal.io.ResourceFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DroolsConfig {
    // 制定规则文件的路径
    private static final String RULES_CUSTOMER_RULES_DRL = "rules/FeeRule.drl";

    @Bean
    public KieContainer kieContainer() {
        KieServices kieServices = KieServices.Factory.get();

        KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
        kieFileSystem.write(ResourceFactory.newClassPathResource(RULES_CUSTOMER_RULES_DRL));
        KieBuilder kb = kieServices.newKieBuilder(kieFileSystem);
        kb.buildAll();

        KieModule kieModule = kb.getKieModule();
        KieContainer kieContainer = kieServices.newKieContainer(kieModule.getReleaseId());
        return kieContainer;
    }
}

/**
 * drools的使用首先是引入依赖，之后配置该配置类，拿到kiecontainer
 * 之后在需要使用的地方直接注入kiecontainer， 还要去用它创建一个会话KieSession kieSession = kieContainer.newKieSession();
 * 再之后才是拿这个会话去执行规则
 * kieSession.insert();  插入drl文件中用到的对象，即在when代码块里拿到的类
 * kieSession.fireAllRules();   执行规则
 * kieSession.dispose();   关闭
 * 若是有全局变量，setglocal后在drl执行后，java代码里也能拿到执行的值
 */